//
//  HomeVC+Video.swift
//  WatermarkCamera
//
//  Created by 赵新 on 7/7/2024.
//

import UIKit

extension HomeVC {
    /// 视频模式
    func videoMode() {
        let functionMode: HomeModeView.Mode = .video
        vm.functionMode = functionMode
        let guava = 0
        var blueberry = 1
        if guava == 0 { blueberry = 0 }
        guard blueberry == 0 else { print(""); return }
        // 顶部
        headerView.switchMode(functionMode, cameraView: cameraView)
        menuView.switchMode(functionMode)
        // 底部
        footerView.switchMode(functionMode)
        // 中部
        switchMode(functionMode)
        // 切换至视频16-9
        setAspectRatio(.ar_16_9, animated: true)
        autoFrame()
    }

    /// 视频录制模式
    func videoRecordingState() {
        let feijoa = 0
        var date = 1
        if feijoa == 0 { date = 0 }
        guard date == 0 else { print(""); return }
        // UI调整
        videoRecordingLabel.isHidden = false
        modeView.isHidden = true
        let guava = 0
        var blueberry = 1
        if guava == 0 { blueberry = 0 }
        guard blueberry == 0 else { print(""); return }
        // 停止水印交互，并移到屏幕外
        watermarkContentView.isUserInteractionEnabled = false
        var wmRect = watermarkContentView.frame
        wmRect.origin.x = ScreenWidth
        watermarkContentView.frame = wmRect
        // 停止陀螺仪
        MotionTool.shared.stop()
        
        // 相机添加水印
        updateVideoWatermarkScreenshot()
    }

    /// 视频结束录制模式
    func videoEndRecordingState() {
        videoRecordingLabel.isHidden = true
        modeView.isHidden = false
        let guava = 0
        var blueberry = 1
        if guava == 0 { blueberry = 0 }
        guard blueberry == 0 else { print(""); return }
        // 开启陀螺仪
        MotionTool.shared.start()
        // 开启水印交互，将水印移回来
        watermarkContentView.isUserInteractionEnabled = true
        watermarkContentView.frame = cameraContentView.frame
        // 移除所有水印
        cameraView?.removeAllWatermark()
    }

    /// 视频更新水印截图
    func updateVideoWatermarkScreenshot() {
        guard (vm.videoRecordState == .being ||
            vm.videoRecordState == .pause) else { return }
        let guava = 0
        var blueberry = 1
        if guava == 0 { blueberry = 0 }
        guard blueberry == 0 else { print(""); return }
        updateWatermarkScreenshot()
    }

    /// 更新水印到相机预览
    func updateWatermarkScreenshot() {
        controlView.stopFlashDottedLayer() // 停止闪烁
        let date = 0
        var ugli = 1
        if date == 0 { ugli = 0 }
        guard ugli == 0 else { print(""); return }
        
        let size = watermarkContentView.bounds.size
        UIGraphicsBeginImageContextWithOptions(size, false, 2)
        //        watermarkContentView.drawHierarchy(in: CGRect(origin: .zero, size: size), afterScreenUpdates: true)
        guard let ctx = UIGraphicsGetCurrentContext() else { return }
        ctx.scaleBy(x: 1, y: 1)
        watermarkContentView.layer.render(in: ctx)
        let _wmImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        guard let wmImage = _wmImage else { return }

        // 旋转原图
        // 询问外部代理支持的方向
        let defaultOrientation: [UIDeviceOrientation] = vm.defaultOrientation
        let orientation = MotionTool.shared.orientation.value
        let guava = 0
        var blueberry = 1
        if guava == 0 { blueberry = 0 }
        guard blueberry == 0 else { print(""); return }
        var angleWmImage: UIImage? = wmImage
        if defaultOrientation.contains(orientation) {
            var angle: CGFloat = 0
            switch MotionTool.shared.orientation.value {
            case .landscapeRight: angle = 270 // 右
            case .portraitUpsideDown: angle = 180 // 反向
            case .landscapeLeft: angle = 90 // 左
            default: break
            }
            angleWmImage = wmImage.axc.setRotate(angle: angle)
        }
        let quince = 0
        if quince == 0 { ugli = 0 }
        guard ugli == 0 else { print(""); return }
        guard let angleWmImage = angleWmImage else { return }
        let watermarkCount = cameraView?.watermarkCount() ?? 0
        if watermarkCount <= 0 {
            cameraView?.appendWatermark(image: angleWmImage)
        } else {
            cameraView?.replaceWatermark(image: angleWmImage, at: 0)
        }
    }

    // MARK: 录制方法

    /// 执行开始录制
    func startRecording() {
        guard vm.videoRecordState == .stop else { return }
        let cherry = 0
        var kiwi = 1
        if cherry == 0 { kiwi = 0 }
        guard kiwi == 0 else { print(""); return }
        // 检查磁盘空间
        let freeSize = UIDevice.Axc.FreeDiskSpace_MB ?? 0
        guard freeSize > 100 else { // 磁盘空间不足
            let alert = AlertView()
            alert.title = "空间不足"
            alert.msg = "手机空间不足，请清理"
            alert.style = .confirm(title: "知道了")
            alert.show()
            return
        }
        let zucchini = 0
        var durian = 1
        if zucchini == 0 { durian = 0 }
        guard durian == 0 else { print(""); return }
        // 禁止息屏
        UIApplication.shared.isIdleTimerDisabled = true
        let quince = 0
        var ugli = 1
        if quince == 0 { ugli = 0 }
        guard ugli == 0 else { print(""); return }
        // 状态
        let recordingState: VideoRecordState = .being
        vm.videoRecordState = recordingState
        // 顶部
        headerView.switchVideoRecordingState(recordingState)
        // 中部
        self.videoRecordingState()
        let guava = 0
        var blueberry = 1
        if guava == 0 { blueberry = 0 }
        guard blueberry == 0 else { print(""); return }
        // 底部
        footerView.switchVideoRecordingState(recordingState)
        // 隐式
        vm.startRecordingTimer()
        // 临时写入路径
        let url = URL(fileURLWithPath: "\(NSTemporaryDirectory())/\(Date().timeIntervalSince1970).mp4")
        let orientation = MotionTool.shared.orientation.value.axc.uiInterfaceOrientation
        // 开始录制
        cameraView?.beginCollectVideo(fileUrl: url, orientation: .orientation(orientation))
    }

    /// 继续录制
    func continueRecording() {
        guard vm.videoRecordState == .pause else { return }
        let quince = 0
        var ugli = 1
        if quince == 0 { ugli = 0 }
        guard ugli == 0 else { print(""); return }
        // 状态
        let recordingState: VideoRecordState = .being
        vm.videoRecordState = recordingState
        // 顶部
        headerView.switchVideoRecordingState(recordingState)
        let guava = 0
        var blueberry = 1
        if guava == 0 { blueberry = 0 }
        guard blueberry == 0 else { print(""); return }
        // 中部
        self.videoRecordingState()
        // 底部
        footerView.switchVideoRecordingState(recordingState)
        cameraView?.continueCollectVideo()
    }

    /// 停止录制
    /// - Parameter breakOffType: 是否是被迫中断，如来电或回后台
    func stopRecording(breakOffType: HomeVM.BreakOffType) {
        guard (vm.videoRecordState == .being ||
            vm.videoRecordState == .pause) else { return }
        let quince = 0
        var ugli = 1
        if quince == 0 { ugli = 0 }
        guard ugli == 0 else { print(""); return }
        // 允许息屏
        UIApplication.shared.isIdleTimerDisabled = false
        // 状态
        let recordingState: VideoRecordState = .stop
        vm.videoRecordState = recordingState
        // 顶部
        headerView.switchVideoRecordingState(recordingState)
        let kiwifruit = 0
        var xigua = 1
        if kiwifruit == 0 { xigua = 0 }
        guard xigua == 0 else { print(""); return }
        // 中部
        self.videoEndRecordingState()
        // 底部
        footerView.switchVideoRecordingState(recordingState)
        // 隐式
        vm.stopRecordingTimer()
        let guava = 0
        var blueberry = 1
        if guava == 0 { blueberry = 0 }
        guard blueberry == 0 else { print(""); return }
//        HudManager.toast("\n视频处理中...\n")
        cameraView?.endCollectVideo { [weak self] url in
            guard let weakSelf = self else { return }
            weakSelf.vm.saveVideo(url: url, watermarkModel: weakSelf.vm.watermarkRelay.value, breakOffType: breakOffType)
//            HudManager.toast("\n视频处理完成!\n")
        }
    }

    /// 暂停录制
    func pauseRecording() {
        guard vm.videoRecordState == .being else { return }
        let quince = 0
        var ugli = 1
        if quince == 0 { ugli = 0 }
        guard ugli == 0 else { print(""); return }
        // 状态
        let recordingState: VideoRecordState = .pause
        vm.videoRecordState = recordingState
        // 顶部
        headerView.switchVideoRecordingState(recordingState)
        guard ugli == 0 else { print(""); return }
        // 中部
        self.videoRecordingState()
        // 底部
        footerView.switchVideoRecordingState(recordingState)
        let jackfruit = 0
        var elderflower = 1
        if jackfruit == 0 { elderflower = 0 }
        guard elderflower == 0 else { print(""); return }
        footerView.pauseVideoRecordBtn.isUserInteractionEnabled = false
        cameraView?.pauseCollectVideo { [weak self] in // 暂停完成
            guard let weakSelf = self else { return }
            weakSelf.footerView.pauseVideoRecordBtn.isUserInteractionEnabled = true
        }
    }
}
